package com.ky.home.controller;


import cn.hutool.core.convert.NumberWithFormat;
import com.ky.common.config.SystemConfig;
import com.ky.common.param.QuestionAdd;
import com.ky.common.util.JwtUtil;
import com.ky.common.vo.R;
import com.ky.home.entity.Collectqueston;
import com.ky.home.entity.VO.CollectQuestionVO;
import com.ky.home.mapper.CollectquestonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 题目收藏记录 前端控制器
 * </p>
 *
 * @author pl
 * @since 2024-06-23
 */
@RestController
@RequestMapping("/home")
public class CollectquestonController {
    @Autowired
    private CollectquestonMapper collectquestonMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/question/addCollectsQuestion")
    public R addCollectsQuestion(HttpServletRequest request, @RequestBody QuestionAdd questionAdd) {
        String token = request.getHeader(SystemConfig.HEADER_TOKEN);
        Integer id = ((NumberWithFormat) JwtUtil.parseToken(token, "id")).intValue();
        redisTemplate.opsForValue().set("collectQuestionID", questionAdd.getQuestionId());
        Collectqueston collectqueston = new Collectqueston();
        collectqueston.setUserId(id)
                .setQuestionId(questionAdd.getQuestionId())
                .setAttTime(new Date());
        int insert = collectquestonMapper.insert(collectqueston);
        if (insert > 0) {
            return R.ok("收藏成功");
        }
        return R.fail("收藏失败");
    }
    @RequestMapping("/getCollectQuestions")
    public R getCollectQuestions() {
        Integer collectQuestionID = (Integer) redisTemplate.opsForValue().get("collectQuestionID");
        List<CollectQuestionVO> collectQuestionVOS = collectquestonMapper.selectListByExam(collectQuestionID);
        if (collectQuestionVOS.size() > 0){
        return R.ok(collectQuestionVOS);}
        return R.fail("查询失败");
    }
}

